package com.justnow;

import java.util.concurrent.locks.AbstractQueuedSynchronizer;

public class SelfAQS {
    private final Sync sync = new Sync();

    public void lock() {
        sync.acquire(1);
    }

    public boolean tryLock() {
        return sync.tryAcquire(1);
    }

    public boolean unLock() {
        return sync.release(1);
    }

    //定义一个Sync来继承抽象类
    static class Sync extends AbstractQueuedSynchronizer {

        /**
         * 获取同步资源
         * @param arg
         * @return
         */
        @Override
        protected boolean tryAcquire(int arg) {
            if (compareAndSetState(0, 1)) {
                //设置拿到锁的线程为当前线程
                setExclusiveOwnerThread(Thread.currentThread());
                return true;
            }
            return false;
        }

        /**
         * 释放同步资源
         * @param arg
         * @return
         */
        @Override
        protected boolean tryRelease(int arg) {
            if (getState() == 0)
                throw new IllegalMonitorStateException();
            setExclusiveOwnerThread(null);
            setState(0);
            return true;
        }

        //当前同步器是否在独占模式下被线程占用
        @Override
        protected boolean isHeldExclusively() {
            return getState() == 1;
        }
    }
}
